<script setup>
import { ref, onMounted } from 'vue'
import { ElTable, ElTableColumn, ElPagination, ElInput, ElButton, ElIcon, ElDialog, ElForm, ElFormItem, ElMessage, ElMessageBox } from 'element-plus'
import { Search, Edit, Plus, Delete } from '@element-plus/icons-vue'
import courseApi from '../../../api/course.js'

// 定义表格数据
const courseData = ref([])
// 分页数据
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)

// 新增/编辑弹窗相关
const dialogVisible = ref(false)
const isEditMode = ref(false)
const dialogLoading = ref(false)
const formData = ref({
  id: '',
  courseName: '',
  credits: null,
  hours: null
})

const formRules = {
  courseName: [
    { required: true, message: '请输入课程名称', trigger: 'blur' },
    { min: 1, max: 50, message: '课程名称长度在 1 到 50 个字符', trigger: 'blur' }
  ],
  credits: [
    { required: true, message: '请输入学分', trigger: 'blur' },
    { type: 'number', min: 0, max: 10, message: '学分必须在0-10之间', trigger: 'blur' }
  ],
  hours: [
    { required: true, message: '请输入课时', trigger: 'blur' },
    { type: 'number', min: 0, message: '课时必须大于0', trigger: 'blur' }
  ]
}

// 获取课程分页数据
const getCourseData = async (pageNum = 1, pageSize = 10, courseName = '') => {
  loading.value = true
  try {
    const response = await courseApi.getCoursePage(pageNum, pageSize, courseName)

    if (response && response.code === 200) {
      // 正确处理MyBatis-Plus的Page对象
      courseData.value = response.data.records || []
      pagination.value.total = response.data.total || 0
    } else {
      console.error('获取课程数据失败:', response?.msg || '未知错误')
    }
  } catch (error) {
    console.error('请求课程数据时发生错误:', error)
  } finally {
    loading.value = false
  }
}

// 分页变化时触发
const handleCurrentChange = (currentPage) => {
  pagination.value.currentPage = currentPage
  getCourseData(currentPage, pagination.value.pageSize, searchKeyword.value)
}

// 每页条数变化时触发
const handleSizeChange = (pageSize) => {
  pagination.value.pageSize = pageSize
  getCourseData(pagination.value.currentPage, pageSize, searchKeyword.value)
}

// 搜索课程
const handleSearch = () => {
  pagination.value.currentPage = 1
  getCourseData(1, pagination.value.pageSize, searchKeyword.value)
}

// 打开新增弹窗
const openAddDialog = () => {
  isEditMode.value = false
  formData.value = {
    id: '',
    courseName: '',
    credits: null,
    hours: null
  }
  dialogVisible.value = true
}

// 打开编辑弹窗
const openEditDialog = (course) => {
  isEditMode.value = true
  formData.value = {
    id: course.id,
    courseName: course.courseName,
    credits: course.credits,
    hours: course.hours
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  const sendData = {
    id: isEditMode.value ? formData.value.id : '',
    courseName: formData.value.courseName.trim(),
    credits: Number(formData.value.credits),
    hours: Number(formData.value.hours)
  }
  // 简单的表单验证
  if (!formData.value.courseName || formData.value.credits === null || formData.value.hours === null) {
    ElMessage.warning('请填写完整的课程信息')
    return
  }

  try {
    dialogLoading.value = true
    let response

    if (isEditMode.value) {
      // 更新课程
      response = await courseApi.updateCourse(formData.value)
    } else {
      // 新增课程
      response = await courseApi.addCourse(formData.value)
    }

    if (response && response.code === 200) {
      ElMessage.success(isEditMode.value ? '课程更新成功' : '课程添加成功')
      dialogVisible.value = false
      // 重新加载课程列表
      getCourseData(pagination.value.currentPage, pagination.value.pageSize, searchKeyword.value)
    } else {
      ElMessage.error((isEditMode.value ? '课程更新失败' : '课程添加失败') + ': ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    console.error((isEditMode.value ? '更新课程' : '添加课程') + '时发生错误:', error.message || error)
    // 针对不同类型的错误提供更友好的提示
    if (error.isForbidden || (error.response && error.response.status === 403)) {
      ElMessage.warning('操作需要权限，请先登录或检查权限设置')
    } else {
      ElMessage.error(isEditMode.value ? '课程更新失败' : '课程添加失败')
    }
  } finally {
    dialogLoading.value = false
  }
}

// 删除课程
const deleteCourse = async (courseId, courseName) => {
  try {
    // 弹出确认对话框
    await ElMessageBox.confirm(
        `确定要删除课程 "${courseName}" 吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await courseApi.deleteCourse(courseId)

    if (response && response.code === 200) {
      ElMessage.success('课程删除成功')
      // 重新加载课程列表
      getCourseData(pagination.value.currentPage, pagination.value.pageSize, searchKeyword.value)
    } else {
      ElMessage.error('课程删除失败: ' + (response?.msg || '未知错误'))
    }
  } catch (error) {
    // 用户取消删除操作时不会显示错误信息
    if (error !== 'cancel') {
      console.error('删除课程时发生错误:', error)
      ElMessage.error('课程删除失败')
    }
  }
}

// 初始加载数据
onMounted(() => {
  getCourseData()
})
</script>

<template>
  <div class="course-container">
    <div class="search-bar">
      <ElInput
          v-model="searchKeyword"
          placeholder="请输入课程名称"
          class="search-input"
          :prefix-icon="Search"
      />
      <ElButton type="primary" @click="handleSearch">搜索</ElButton>
      <ElButton type="primary" @click="openAddDialog" :icon="Plus" style="margin-left: 10px">
        新增课程
      </ElButton>
    </div>

    <ElTable
        :data="courseData"
        style="width: 100%"
        v-loading="loading"
        element-loading-text="加载中..."
    >

<!--      <ElTableColumn prop="id" label="课程ID" width="80" />-->
      <ElTableColumn prop="courseName" label="课程名称" width="200" />
      <ElTableColumn prop="credits" label="学分" width="120" />
      <ElTableColumn prop="hours" label="课时" width="120" />
      <ElTableColumn label="操作" width="200" fixed="right">
        <template #default="scope">
          <ElButton
              type="primary"
              size="small"
              @click="openEditDialog(scope.row)"
              :icon="Edit"
              style="margin-right: 10px"
          >
            编辑
          </ElButton>
          <ElButton
              type="danger"
              size="small"
              @click="deleteCourse(scope.row.id, scope.row.courseName)"
              :icon="Delete"
          >
            删除
          </ElButton>
        </template>
      </ElTableColumn>
    </ElTable>

    <div class="pagination-container">
      <ElPagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑弹窗 -->
    <ElDialog
        v-model="dialogVisible"
        :title="isEditMode ? '编辑课程' : '新增课程'"
        width="400px"
        :before-close="() => { dialogVisible.value = false }"
    >
      <ElForm :model="formData" :rules="formRules" label-width="80px" v-loading="dialogLoading">
        <ElFormItem label="课程名称" prop="courseName">
          <ElInput v-model="formData.courseName" placeholder="请输入课程名称" />
        </ElFormItem>
        <ElFormItem label="学分" prop="credits">
          <ElInput v-model.number="formData.credits" type="number" placeholder="请输入学分" />
        </ElFormItem>
        <ElFormItem label="课时" prop="hours">
          <ElInput v-model.number="formData.hours" type="number" placeholder="请输入课时" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="dialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="submitForm">确定</ElButton>
      </template>
    </ElDialog>
  </div>
</template>

<style scoped>
.course-container {
  padding: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
  margin-right: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>